﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using EmoneyWeiXinEntity;
using Newtonsoft.Json.Linq;
namespace EmoneyWeiXinCommon
{
    public class TokenHelper
    {
        #region 获得Token
        /// <summary>
        /// 获得Ticket
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appsecret"></param>
        /// <returns></returns>
        public static string GetTicket(string appid = "", string appsecret = "")
        {
            string key = "GetTicket" + appid;
            MemcachedTools1 memcachedTools = new MemcachedTools1();
            string ticket = memcachedTools.Get<string>(key);
            if (string.IsNullOrEmpty(ticket))
            {

                string strToken = GetToken(appid, appsecret);
                if (!string.IsNullOrEmpty(strToken))
                {
                    Dictionary<string, string> urlParams = new Dictionary<string, string>();
                    urlParams.Add("access_token", strToken);
                    urlParams.Add("type", "jsapi");
                    string ret = NetHelper.LoadData(Config.WeiXin_ApiUrl + "ticket/getticket", urlParams);
                    if (!string.IsNullOrEmpty(ret))
                    {
                        ticketEntity1 ticketE = JsonTools.ToObject<ticketEntity1>(ret);
                        if (ticketE != null && ticketE.errcode == 0)
                        {
                            ticket = ticketE.ticket;
                            MyTrace.get().add("getWxTicket----从响应数据中取出：ticket" + ticket);
                            memcachedTools.Add(key, ticket, 1, 0, 0);
                        }
                    }
                }
            }
            return ticket;
        }
        #endregion

        #region 获得Token
        /// <summary>
        /// 获得Token
        /// </summary>
        /// <returns></returns>
        public static string GetToken(string appid, string appsercret)
        {
            //string key = CacheManager.GetCachedKey("GetToken");
            //string token = CacheManager.RedisCache.Get<string>(key);
            var key = Config.MemcachedKey + ".TokenHelper.GetToken." + appid;
            var token = "";
            var ob = MemcachedTools.Get(key);
            if (ob != null)
                token = ob.ToString();
            if (string.IsNullOrEmpty(token))
            {
                Dictionary<string, string> urlParams = new Dictionary<string, string>();
                urlParams.Add("grant_type", "client_credential");
                urlParams.Add("appid", appid);
                urlParams.Add("secret", appsercret);
                string url = Config.WeiXin_ApiUrl + "token";
                string ret = NetHelper.LoadData(url, urlParams);
                MyTrace.get().add("GetToken:ret:" + ret);
                JObject jObj = JObject.Parse(ret);
                if (jObj != null)
                {
                    JToken jToken;
                    if (jObj.TryGetValue("access_token", out jToken))
                    {
                        token = jObj["access_token"].ToString().Replace("\"", "");
                        if (!string.IsNullOrEmpty(token))
                        {
                            //CacheManager.RedisCache.Set<String>(key, token, 60);
                            MemcachedTools.Add(key, token, System.DateTime.Now.AddMinutes(60));
                        }
                    }
                }
            }
            return token;
        }
        public static void ClearToken()
        {
            //string key = CacheManager.GetCachedKey("GetToken");
            //CacheManager.RedisCache.Remove(key);
            var key = Config.MemcachedKey;
            MemcachedTools.Clear(key);
        }

        public static void ClearToken(string appid)
        {
            //string key = CacheManager.GetCachedKey("GetToken");
            //CacheManager.RedisCache.Remove(key);
            var key = Config.MemcachedKey + ".TokenHelper.GetToken." + appid;
            MemcachedTools.Clear(key);
        }
        #endregion

        #region 获取关注者列表
        //https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID

        public static string GetUser(string appid, string acctoken, string nextopenid)
        {
            string key = "GetUser" + appid + nextopenid;
            MemcachedTools1 memcachedTools = new MemcachedTools1();
            string result = "";
            //string result = memcachedTools.Get<string>(key);
            if (string.IsNullOrEmpty(result))
            {
                Dictionary<string, string> urlParams = new Dictionary<string, string>();
                urlParams.Add("grant_type", "client_credential");
                urlParams.Add("access_token", acctoken);
                urlParams.Add("next_openid", nextopenid);

                string url = Config.WeiXin_ApiUrl + "user/get";
                string ret = NetHelper.LoadData(url, urlParams);

                if (!string.IsNullOrEmpty(ret))
                {
                    result = ret;
                    memcachedTools.Add(key, ret, 0, 5, 0);
                }
            }
            return result;
        }
        #endregion

        //Post请求方式，于Get的方式写法相似，所以解释就些少一点了
        //两个参数分别是Url地址和Post过去的数据
        public static string RequestPost(string Url, string Context)
        {
            string PageStr = string.Empty;
            Uri url = new Uri(Url);
            byte[] reqbytes = Encoding.UTF8.GetBytes(Context);
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "post";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = reqbytes.Length;
                Stream stm = req.GetRequestStream();
                stm.Write(reqbytes, 0, reqbytes.Length);

                stm.Close();
                HttpWebResponse wr = (HttpWebResponse)req.GetResponse();
                Stream stream = wr.GetResponseStream();
                StreamReader srd = new StreamReader(stream, Encoding.GetEncoding("gb2312"));
                PageStr += srd.ReadToEnd();
                stream.Close();
                srd.Close();
            }
            catch (Exception e)
            {
                PageStr += e.Message;
            }
            return PageStr;
        }
    }
}